# -- coding: utf-8 --
# @time : 2023/5/26
# @author : 周梦泽
# @file : get_goods.py
# @software: pycharm
# 获取店铺的所有商品
import base64
import re
from dataclasses import dataclass
from datetime import datetime
from typing import Union

from autoTask.taobao.taobao_login import Login
from common.utils.web_page_util import MockTap
from common.logger.log import log_
import requests
from PIL import Image
from io import BytesIO
from autoTask.operaitonAid.utils.taobao_requests_headers import page_headers


@dataclass
class ProductInfo:
    """
    商品信息
    """
    id: int
    title: str
    price: float
    img_url: str
    img: Image
    stock: str
    # 商品库存
    sales: float
    quality: str
    create_time: datetime

    @property
    def img_base64(self):
        if self.img:
            with BytesIO() as buffer:
                self.img.save(buffer, format="PNG")
                img_base64 = base64.b64encode(buffer.getvalue()).decode("utf-8")
            return img_base64
        else:
            raise ValueError("img参数为空，无法将其base64")


class GetProductInfo:

    def __init__(self, params: dict):
        """
        初始化参数
        :param params: 任务参数 包含
                ['tbAccount': 账号 str,
                'tbPassword':密码 str,

                ]
        """
        self.account = params['account']
        self.password = params['password']
        self.page, _ = Login(self.account, self.password).execute()
        self.headers = page_headers(self.page)

    def get_product_info(self) -> Union[list[ProductInfo], None]:
        """
        获取店铺的所有商品信息
        :return:
        """
        if self.page.url != "https://myseller.taobao.com/home.htm/QnworkbenchHome/":
            self.page.get("https://myseller.taobao.com/home.htm/QnworkbenchHome/")
        MockTap("tag=span@@text()=商品", before_delay=(2, 3), after_delay=(2, 3), reduce_scope=(1, 10),
                msg="点击商品标签页失败")(self.page)
        product_info_obj_list = []
        # 商品信息对象列表
        while True:
            next_page = self.page(
                "x://div[contains(@class, 'config-list-simple-pagination')]//i[contains(@class, 'right')]")
            next_page_states = eval(self.page("x://span[@class='next-pagination-display']").text)
            print(next_page_states)
            product_list = self.page.eles("x://tr[contains(@class, 'row-with-config-list')]")
            log_.info("正在获取商品信息")
            for product in product_list:
                product_title = product("x://td[contains(@label, '商品名称')]//span/a").text
                # 商品标题
                product_id = int(product("x://td[contains(@label, '商品名称')]//span/a").link.split('=')[-1])
                # print(product_id)
                product_img_url = \
                    product(
                        "x://td[contains(@label, '商品名称')]//img[@class='product-desc-extend-image']").link.replace(
                        "_160x160xz_.webp", "")
                # print(product_img_url)
                # 商品图片url
                product_img = Image.open(BytesIO(requests.get(product_img_url, headers=self.headers).content))

                # 商品id
                product_price = float(
                    re.search(r'\d+(\.\d+)?', product("x://td[contains(@label, '价格')]//div").text).group(0))
                # 商品价格
                product_stock = product("x://td[contains(@label, '库存')]//div").text
                # 商品库存
                product_sales = float(product("x://td[contains(@label, '销量')]//div").text)
                # 商品销量
                product_quality = product("x://td[contains(@label, '信息质量')]//div//span").text
                # 商品信息质量
                product_create_time = datetime.strptime(
                    product("x://td[contains(@label, '创建时间')]//div[@class='product-desc-span']").text,
                    "%Y-%m-%d %H:%M")
                # 商品创建时间
                product_info_obj_list.append(
                    ProductInfo(product_id, product_title, product_price, product_img_url, product_img, product_stock,
                                product_sales, product_quality, product_create_time)
                )

            if next_page_states == 1:
                break
            else:
                MockTap(next_page, before_delay=(2, 3), after_delay=(2, 3), reduce_scope=(1, 10),
                        msg="点击下一页失败")()
            if not product_list:
                log_.info("没有商品")
                return None
        return product_info_obj_list
